/* 
 * AUTHOR: Kevin Lam
 */

package com.apps.ubc.cc.ajax;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringEscapeUtils;

import com.apps.datastore.dao.BookInformation;
import com.apps.services.SaveonbookService;
import com.apps.services.factory.SaveonBookServiceFactory;
import com.apps.ubc.cc.model.SaveonBookModel;
import com.apps.utils.UrlEncodingUtils;



public class SaveonBookController extends HttpServlet{
	
	SaveonbookService sbss = SaveonBookServiceFactory.getSaveonbookService();
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) {
		String title = UrlEncodingUtils.decodeURL(req.getParameter("title"));
		String author =  UrlEncodingUtils.decodeURL(req.getParameter("author"));
		String isbn =  UrlEncodingUtils.decodeURL(req.getParameter("isbn"));
		BookInformation bi = new BookInformation(title,"",author, isbn);
		String optimizedtitle = sbss.getOptimizedTitle(bi);
		List<SaveonBookModel> sbml = sbss.titleSearch(optimizedtitle);
		int[] priceRange = sbss.getPriceRange(sbml);
		String low = "$"+priceRange[0];
		String high = "$"+priceRange[1];
		String out = "<book>\n";
		out += "\t<title>"+StringEscapeUtils.escapeXml(optimizedtitle)+"</title>\n";
		String encodedURL = optimizedtitle;
		if(optimizedtitle.contains("'"))
			encodedURL = encodedURL.substring(0,optimizedtitle.indexOf("'")); //SBK has bad SQL injection handling so must remove all characters in the title proceeding the ' symbol including the ' symbol itself.
		try {
			encodedURL = URLEncoder.encode(optimizedtitle,"UTF-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		out += "\t<detail>"+StringEscapeUtils.escapeXml("http://saveonbook.com/search/title-search.jsp?title="+encodedURL+"&active=0")+"</detail>\n";
		out += "\t<lowestPrice>"+low+"</lowestPrice>\n";
		out += "\t<highestPrice>"+high+"</highestPrice>\n";
		out += "</book>";
		try {
			resp.setContentType("text/xml");
			resp.getWriter().write(out);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

}
